package cn.edu.nju.ws.sview.reasoning.schema;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;

/**
 * 为类ClassTree服务，
 * @author Saisai Gong
 *
 */
public class ClassTreeNode implements Comparable<ClassTreeNode> {
	//强连通分支压缩后，并逆拓扑排序后的节点编号id，这个节点代表一个强连通分支
	private int nodeID;
	//这个节点（强连通分支）里面包含的类的集合
	private HashSet<Integer> classes;
	//这个集合的代表类id，为前端界面服务
	private int agentClassID;
	//无序的邻居表
	private HashSet<ClassTreeNode> unorderNeighbors;
	//有序的邻接表
	private ArrayList<ClassTreeNode> neighbors = null;

	@Override
	public int compareTo(ClassTreeNode arg0) {
		// TODO Auto-generated method stub
		return (arg0.nodeID-this.nodeID);
	}
	
	/**
	 * 构造函数
	 * @param nodeID.逆拓扑排序中的编号，排序最靠前的从0开始
	 * @param classes.这个节点代表的强连通分支包含的类id
	 */
	public ClassTreeNode(int nodeID, HashSet<Integer> classes){
		this.nodeID = nodeID;
		this.classes = new HashSet<Integer>();
		this.classes.addAll(classes);
		this.unorderNeighbors = new HashSet<ClassTreeNode>();
	}
	
	public int getNodeID(){
		return this.nodeID;
	}
	
	public HashSet<Integer> getClasses(){
		return this.classes;
	}
	
	public int getAgentClassID(){
		if(this.agentClassID==0){
			for(Integer classID:classes){
				this.agentClassID = classID;
				break;
			}
		}
		return this.agentClassID;
	}
	
	public void addNeighbor(ClassTreeNode node){
		this.unorderNeighbors.add(node);
	}
	
	public void deleteNeighbor(ClassTreeNode node){
		this.neighbors = null;
		this.unorderNeighbors.remove(node);
	}
	
	//返回排序的邻接表
	public ArrayList<ClassTreeNode> getOrderNeighbors(){
		if(neighbors==null){
			neighbors =new ArrayList<ClassTreeNode>(this.unorderNeighbors);
			Collections.sort(neighbors);
		}
		return neighbors;
	}
	

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + nodeID;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ClassTreeNode other = (ClassTreeNode) obj;
		if (nodeID != other.nodeID)
			return false;
		return true;
	}
	
	public String toString(){
		StringBuffer buffer = new StringBuffer();
		buffer.append("Node: "+this.nodeID+" : ( ");
		ArrayList<ClassTreeNode> neighbors = this.getOrderNeighbors();
		for(int i=0;i<neighbors.size();i++){
			ClassTreeNode node = neighbors.get(i);
			int nodeID = node.getNodeID();
			buffer.append(nodeID);
			if(i!=neighbors.size()-1){
				buffer.append(" , ");
			}
		}
		buffer.append(" )");
		return buffer.toString();
	}
 
}
